'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Category.belongsToMany(models.Article, { through: models.CategoryArticle, foreignKey: 'categoryId', as: 'articles' });
    }
  }
  Category.init({
    nameZh: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '中文分类名称必填'},
        notEmpty: {msg: '中文分类名称不能为空'},
        len: {
          args: [2, 45],
          msg: '中文分类名称长度在2-45个字符之间'
        },
        async isUnique(value) {
          const category = await Category.findOne({ where: { nameZh: value } })
          if (category) {
            throw new Error('中文分类名称已经存在。');
          }
        }
      }
    },
    nameEn: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '英文分类名称必填'},
        notEmpty: {msg: '英文分类名称不能为空'},
        len: {
          args: [2, 45],
          msg: '英文分类名称长度在2-45个字符之间'
        },
        async isUnique(value) {
          const category = await Category.findOne({ where: { nameEn: value } })
          if (category) {
            throw new Error('英文分类名称已经存在。');
          }
        }
      }
    },
    status: {
      allowNull: false,
      defaultValue: 2,
      type: DataTypes.ENUM('1', '2'),
      validate: {
        isIn: {
          args: [['1', '2']],
          msg: '状态值必须是 1（上架）、2（下架）之一'
        }
      }
    },
    rank: {
      allowNull: false,
      type: DataTypes.INTEGER,
      defaultValue: 1
    },
  }, {
    sequelize,
    modelName: 'Category',
  });
  return Category;
};